<?php

namespace lite\controllers;

use common\libs\Util;
use weixin\models\game\AR\ProofAR;
use weixin\models\game\Game;
use weixin\models\user\AR\UserAR;
use lite\models\Weixin;
use Yii;
use lite\libs\CommonController;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

class QiniuController extends CommonController {

    private $auth;
    public $layout = false;

    public function actionQiniu_token() {
        $this->generateQiniuAuth();
        $bucket = Yii::$app->params['Qiniu']['bucket'];
        $uptoken = $this->auth->uploadToken($bucket);
        return json_encode(['uptoken' => $uptoken]);
    }

    public function actionQiniu_download_url() {
        $url = Yii::$app->request->post("url");
        $this->generateQiniuAuth();
        return $this->ajaxResponseSuccess(['url' => $this->auth->privateDownloadUrl($url)]);
    }

    public function actionUpload_photo() {
        $accessToken = yii::$app->request->post('access_token');
        $game_id = yii::$app->request->post('game_id');
        $user = Weixin::checkIsLogin($accessToken);
        if($user === false) {
            return $this->ajaxResponseError('用户还未登录，请重新登录', -999);
        }
        $fileResult = $_FILES['key'];
        $this->generateQiniuAuth();
        $bucket = Yii::$app->params['Qiniu']['bucket'];

        $uptoken = $this->auth->uploadToken($bucket);
        $content = file_get_contents($fileResult['tmp_name']);
        $upload = new UploadManager();
        list($ret, $err) = $upload->put($uptoken, "weixin/media/game_{$game_id}/user_{$user->id}/" . time() . Util::getRandCode(8) . '.jpg', $content);
        if($err !== null) {
            return $this->ajaxResponseError($err);
        }
        $imageUrl = yii::$app->params['pictureStaticUrl'] . '/' . $ret['key'];
        $game = new Game();
        $result = $game->uploadProof($game_id, $user->id, $imageUrl);
        if($result) {
            return $this->ajaxResponseSuccess($result);

        } else {
            return $this->ajaxResponseError($game->getErrMsg());
        }
    }

    public function actionUpload_file() {
        $user_id = yii::$app->session->get('user_id');
        $serviceId = yii::$app->request->post('service_id');
        $game_id = yii::$app->request->post('game_id');

        if(!$user_id) {
            return $this->ajaxResponseNotLogin();
        }
        $weixin = new Weixin();
        $fileResult = $weixin->getFileUrl($serviceId);
        if(false === $fileResult) {
            return $this->ajaxResponseError($weixin->getErrMsg());
        }
        $this->generateQiniuAuth();
        $bucket = Yii::$app->params['Qiniu']['bucket'];
        $uptoken = $this->auth->uploadToken($bucket);
        //$fileName = basename($fileResult['url']);
        $content = $fileResult['file'];
        $upload = new UploadManager();
        list($ret, $err) = $upload->put($uptoken, "weixin/media/game_{$game_id}/user_{$user_id}/" . time() . Util::getRandCode(8) . '.jpg', $content);
        if($err !== null) {
            return $this->ajaxResponseError($err);
        }
        $imageUrl = yii::$app->params['pictureStaticUrl'] . '/' . $ret['key'];
        $game = new Game();
        $result = $game->uploadProof($game_id, $user_id, $imageUrl);
        if($result) {
            return $this->ajaxResponseSuccess($result);
        } else {
            return $this->ajaxResponseError($game->getErrMsg(), -1);
        }
    }

    public function actionUpload_player_image() {
        $serviceId = yii::$app->request->post('service_id');
        $user_id = yii::$app->request->post('user_id');


        $user = UserAR::findOne(['id' => $user_id]);
        if(!$user) {
            return $this->ajaxResponseError('用户信息不正确');
        }
        $weixin = new Weixin();
        $fileResult = $weixin->getFileUrl($serviceId);
        if(false === $fileResult) {
            return $this->ajaxResponseError($weixin->getErrMsg());
        }
        $this->generateQiniuAuth();
        $bucket = Yii::$app->params['Qiniu']['bucket'];
        $uptoken = $this->auth->uploadToken($bucket);
        //$fileName = basename($fileResult['url']);
        $content = $fileResult['file'];
        $upload = new UploadManager();
        list($ret, $err) = $upload->put($uptoken, "weixin/media/user_{$user_id}/" . time() . Util::getRandCode(8) . '.jpg', $content);
        if($err !== null) {
            return $this->ajaxResponseError($err);
        }
        $imageUrl = yii::$app->params['pictureStaticUrl'] . '/' . $ret['key'];

        $weixin = new Weixin();
        $result = $weixin->sendTemplateMessage('send_photo', $user->weixin_openid, ['url' => $imageUrl,
                                                                                    'first' => "亲爱的{$user->name}，您在游戏中的剧照已经上传完成",
                                                                                    'keyword1' => '1张',
                                                                                    'keyword2' => date('Y-m-d H:i:s'),
                                                                                    'remark' => '您可以通过点击详情浏览照片或下载',]);
        if($result) {
            return $this->ajaxResponseSuccess('照片已上传');
        } else {
            return $this->ajaxResponseError($weixin->getErrMsg(), -1);
        }
    }

    private function generateQiniuAuth() {
        if(!$this->auth) {
            $access_key = Yii::$app->params['Qiniu']['access_key'];
            $secret_key = Yii::$app->params['Qiniu']['secret_key'];
            $this->auth = new Auth($access_key, $secret_key);
        }

    }

    /** 文件转base64输出
     * @param  String $file 文件路径
     * @return String base64 string
     */
    private function fileToBase64($file) {
        $base64_file = '';
        if(file_exists($file)) {
            $mime_type = mime_content_type($file);
            $base64_data = base64_encode(file_get_contents($file));
            $base64_file = 'data:' . $mime_type . ';base64,' . $base64_data;
        }
        return $base64_file;
    }

}